package com.example.service;

import com.example.entity.FeePayment;
import com.example.entity.FeeRecord;
import com.example.mapper.FeePaymentMapper;
import com.example.mapper.FeeRecordMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class FeeService {
    
    @Autowired
    private FeeRecordMapper recordMapper;
    
    @Autowired
    private FeePaymentMapper paymentMapper;
    
    @Autowired
    private OrganizationMemberService memberService;
    
    public PageInfo<FeeRecord> page(FeeRecord query, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<FeeRecord> list = recordMapper.selectList(query);
        return new PageInfo<>(list);
    }
    
    public void publish(FeeRecord record) {
        record.setPublishTime(new Date());
        recordMapper.insert(record);
    }
    
    public void pay(Long recordId, Long userId, Integer paymentMethod) {
        // 检查是否已缴费
        FeePayment exists = paymentMapper.selectByRecordAndUser(recordId, userId);
        if (exists != null && exists.getPaymentStatus() == 1) {
            throw new RuntimeException("已缴费,请勿重复缴费");
        }
        
        // 创建支付记录
        FeePayment payment = new FeePayment();
        payment.setFeeRecordId(recordId);
        payment.setUserId(userId);
        payment.setPaymentMethod(paymentMethod);
        payment.setPaymentStatus(1);
        payment.setPaymentTime(new Date());
        
        if (exists == null) {
            paymentMapper.insert(payment);
        } else {
            paymentMapper.updateStatus(exists.getId(), 1, new Date());
        }
    }

    public void delete(int id) {
        paymentMapper.delete(id);
    }
}
